package pri.hillchen.springboot.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pri.hillchen.springboot.shiro.common.util.MessageDigestUtil;

/**
 * Created by hillchen on 2017/10/14.
 */
@Controller
public class LoginController {
    @RequestMapping("/index")
    public String index(){
        return "/index";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/loginUser")
    public String userLogin(String userName, String password, Model model){
        String msg = "";
        UsernamePasswordToken token = new UsernamePasswordToken(userName, MessageDigestUtil.createCredential(password,userName));
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            if (subject.isAuthenticated()) {
                return "/userInfo";
            } else {
                return "/login";
            }
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
            model.addAttribute("message", msg);
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
            model.addAttribute("message", msg);
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
            model.addAttribute("message", msg);
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
            model.addAttribute("message", msg);
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
            model.addAttribute("message", msg);
        } catch (UnknownAccountException e) {
            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
            model.addAttribute("message", msg);
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！" + e.getMessage();
            model.addAttribute("message", msg);
        }
        return "login";
    }


    @RequestMapping("/per1")
    public String per1(){
        return "per1";
    }
    @RequestMapping("/per2")
    public String per2(){
        return "per2";
    }
    @RequestMapping("/per3")
    public String per3(){
        return "per3";
    }
    @RequestMapping("/per4")
    public String per4(){
        return "per4";
    }
}
